#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc, COOPIP_Form, COOPIP_Authentication
from djangoproject.models import *
from django.contrib.gis.geos import *
import GIS, AMR

def BuildNetworkDeviceAddEditForm(SpecialBuildFormDataDict):
    Dict={}
    try:
        networkDevice = SpecialBuildFormDataDict['NetworkDevice']
    except:
        networkDevice = None
    SelectNetworkDeviceChoices=[]
    if(networkDevice):
        SelectNetworkDeviceChoices.append([networkDevice.id, str(networkDevice)])
    SelectNetworkDeviceChoices.append([-1, 'None Selected'])
    NetworkDevices=djangoproject.models.networkdevice.NetworkDevice.objects.all().order_by('Name')
    for i in NetworkDevices:
        if(not [i.id, str(i)] in SelectNetworkDeviceChoices):
            SelectNetworkDeviceChoices.append([i.id, str(i)])
    Dict['SelectNetworkDevice']=forms.ChoiceField(SelectNetworkDeviceChoices, required=False)
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['NewIndicator']=forms.BooleanField(required=False)
    Dict['NetworkDeviceid']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
    Dict['Name']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['Description']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'40'}))
    Dict['IPAddress']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['MACAddress']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['DeviceModel']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['AMRSubstationName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['ServiceTag']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['ServerIndicator']=forms.BooleanField(required=False)
    if not networkDevice:
        return Dict
    DevicePortCount=NetworkDevicePort.objects.filter(NetworkDevice=networkDevice).count()
    for i in range(0, DevicePortCount + 1):
        Dict['Port_id' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
        Dict['NewPortIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['UpdatePortIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['DeletePortIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['PortName' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['PortDescription' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
        Dict['PortMACAddress' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
        Dict['PortIPAddress' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    return Dict

def ProcessNetworkDeviceAddEditForm(form, Username, request):
    SelectNetworkDeviceid=COOPIP_Form.FormGetInteger(form, 'SelectNetworkDevice')
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    NewIndicator=COOPIP_Form.FormGetBoolean(form, 'NewIndicator')
    if(NewIndicator):
        SelectedNetworkDevice=djangoproject.models.networkdevice.NetworkDevice()
    elif(not SelectNetworkDeviceid == -1 and SelectNetworkDeviceid):
        SelectedNetworkDevice=djangoproject.models.networkdevice.NetworkDevice.objects.filter(id=SelectNetworkDeviceid)[0]
    else:
        return #If no Network Device is selected, cannot process changes

    if(NewIndicator or UpdateIndicator):
        SelectedNetworkDevice.Name=COOPIP_Form.FormGetString(form, 'Name')
        SelectedNetworkDevice.Description=COOPIP_Form.FormGetString(form, 'Description')
        SelectedNetworkDevice.IPAddress=COOPIP_Form.FormGetString(form, 'IPAddress')
        SelectedNetworkDevice.MACAddress=COOPIP_Form.FormGetString(form, 'MACAddress')
        SelectedNetworkDevice.DeviceModel=COOPIP_Form.FormGetString(form, 'DeviceModel')
        SelectedNetworkDevice.AMRSubstationName=COOPIP_Form.FormGetString(form, 'AMRSubstationName')
        SelectedNetworkDevice.ServiceTag=COOPIP_Form.FormGetString(form, 'ServiceTag')
        SelectedNetworkDevice.ServerIndicator=COOPIP_Form.FormGetBoolean(form, 'ServerIndicator')
        SelectedNetworkDevice.save()
    NetworkDevicePorts=NetworkDevicePort.objects.filter(NetworkDevice=SelectedNetworkDevice)
    for i in range(0, len(NetworkDevicePorts) + 1):
        UpdatePortIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdatePortIndicator' + str(i))
        DeletePortIndicator=COOPIP_Form.FormGetBoolean(form, 'DeletePortIndicator' + str(i))
        NewPortIndicator=COOPIP_Form.FormGetBoolean(form, 'NewPortIndicator' + str(i))
        Portid=COOPIP_Form.FormGetString(form, 'Port_id' + str(i))
        if UpdatePortIndicator:
            Port=NetworkDevicePort.objects.filter(id=Portid)[0]
            Port.Name=COOPIP_Form.FormGetString(form, 'PortName' + str(i))
            Port.Description=COOPIP_Form.FormGetString(form, 'PortDescription' + str(i))
            Port.MACAddress=COOPIP_Form.FormGetString(form, 'PortMACAddress' + str(i))
            Port.IPAddress=COOPIP_Form.FormGetString(form, 'PortIPAddress' + str(i))
            Port.save()
        elif DeletePortIndicator:
            Port=NetworkDevicePort.objects.filter(id=Portid)[0]
            Port.delete()
        elif NewPortIndicator:
            new=djangoproject.models.networkdevice.NetworkDevicePort()
            new.NetworkDevice=SelectedNetworkDevice
            new.Name=COOPIP_Form.FormGetString(form, 'PortName' + str(i))
            new.Description=COOPIP_Form.FormGetString(form, 'PortDescription' + str(i))
            new.MACAddress=COOPIP_Form.FormGetString(form, 'PortMACAddress' + str(i))
            new.IPAddress=COOPIP_Form.FormGetString(form, 'PortIPAddress' + str(i))
            new.save()
    return SelectedNetworkDevice

def PopulateNetworkDeviceAddEditForm(form, networkDevice):
    form.data['UpdateIndicator']=False
    form.data['NewIndicator']=False

    if(networkDevice):
        form.data['SelectNetworkDevice']=networkDevice.id
        form.data['NetworkDeviceid']=networkDevice.id
        form.data['Name']=networkDevice.Name
        form.data['Description']=networkDevice.Description
        form.data['IPAddress']=networkDevice.IPAddress
        form.data['MACAddress']=networkDevice.MACAddress
        form.data['DeviceModel']=networkDevice.DeviceModel
        form.data['AMRSubstationName']=networkDevice.AMRSubstationName
        form.data['ServiceTag']=networkDevice.ServiceTag
        form.data['ServerIndicator']=networkDevice.ServerIndicator
        NetworkDevicePorts=list(NetworkDevicePort.objects.filter(NetworkDevice=networkDevice))
        for i in range(0, len(NetworkDevicePorts)):
            form.data['Port_id' + str(i)]=NetworkDevicePorts[i].id
            form.data['NewPortIndicator' + str(i)]=False
            form.data['UpdatePortIndicator' + str(i)]=False
            form.data['DeletePortIndicator' + str(i)]=False
            form.data['PortName' + str(i)]=NetworkDevicePorts[i].Name
            form.data['PortDescription' + str(i)]=NetworkDevicePorts[i].Description
            form.data['PortMACAddress' + str(i)]=NetworkDevicePorts[i].MACAddress
            form.data['PortIPAddress' + str(i)]=NetworkDevicePorts[i].IPAddress
    else:
        form.data['SelectNetworkDevice']=''
        form.data['NetworkDeviceid']=''
        form.data['Name']=''
        form.data['Description']=''
        form.data['IPAddress']=''
        form.data['MACAddress']=''
        form.data['DeviceModel']=''
        form.data['AMRSubstationName']=''
        form.data['ServiceTag']=''
        form.data['ServerIndicator']=False
    return form













